package com.aabte.mybatis.plugin;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Statement;
import java.util.Properties;

// 通知Mybatis拦截哪个处理器的哪个方法
@Intercepts(value = {
        @Signature(type = StatementHandler.class, method = "parameterize", args = {Statement.class})
})
public class MyFirstPlugin implements Interceptor {
    /**
     * 拦截目录对象的目标方法的执行
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 执行目标方法
        System.out.println("MyFirstPlugin 拦截目标方法");
        // 获取目标对象
        Object target = invocation.getTarget();
        MetaObject metaObject = SystemMetaObject.forObject(target);
        // 从目标对象获取参数
        Object value = metaObject.getValue("parameterHandler.parameterObject");
        System.out.println("SQL语句用的参数是：" + value);
        // 修改参数
        metaObject.setValue("parameterHandler.parameterObject", 11);
        return invocation.proceed();
    }

    /**
     * 包装目标对象，为目标对象创建代理对象
     * @param target
     * @return
     */
    @Override
    public Object plugin(Object target) {
        System.out.println("MyFirstPlugin 包装目标对象");
        return Plugin.wrap(target, this);
    }

    /**
     * 插件注册时添加property属性
     * @param properties
     */
    @Override
    public void setProperties(Properties properties) {
        System.out.println("MyFirstPlugin 添加配置");
        properties.setProperty("xxx", "yyy");
    }
}
